/**
 ******************************************************************************
 * File Name          : USART.c
 * Description        : This file provides code for the configuration
 *                      of the USART instances.
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2024 STMicroelectronics.
 * All rights reserved.</center></h2>
 *
 * This software component is licensed by ST under BSD 3-Clause license,
 * the "License"; You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *                        opensource.org/licenses/BSD-3-Clause
 *
 ******************************************************************************
 */

/* Includes ------------------------------------------------------------------*/
#include "usart.h"

/* USER CODE BEGIN 0 */
controlinfo_S UartRecData;
uint8_t SYS_DEVADDR = 0x01;
uint8_t SYS_BROADCASTADDR = 0xff;
uint8_t UsartContinuousSendFlag = ORDER_GET_DEV_INF_ascii;
uint8_t rx_data1[1], rx_data2[1];
uint8_t Usart_Send_Buffer[100];
/* USER CODE END 0 */

UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;
DMA_HandleTypeDef hdma_usart1_tx;
DMA_HandleTypeDef hdma_usart2_tx;

/* USART1 init function */

void MX_USART1_UART_Init(void)
{

  huart1.Instance = USART1;
  huart1.Init.BaudRate = 115200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
}
/* USART2 init function */

void MX_USART2_UART_Init(void)
{

  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
}

void HAL_UART_MspInit(UART_HandleTypeDef *uartHandle)
{

  GPIO_InitTypeDef GPIO_InitStruct = {0};
  if (uartHandle->Instance == USART1)
  {
    /* USER CODE BEGIN USART1_MspInit 0 */

    /* USER CODE END USART1_MspInit 0 */
    /* USART1 clock enable */
    __HAL_RCC_USART1_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_9 | GPIO_PIN_10;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF1_USART1;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* USART1 DMA Init */
    /* USART1_TX Init */
    hdma_usart1_tx.Instance = DMA1_Channel2;
    hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
    hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_usart1_tx.Init.Mode = DMA_NORMAL;
    hdma_usart1_tx.Init.Priority = DMA_PRIORITY_LOW;
    if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(uartHandle, hdmatx, hdma_usart1_tx);

    /* USART1 interrupt Init */
    HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USART1_IRQn);
    /* USER CODE BEGIN USART1_MspInit 1 */

    /* USER CODE END USART1_MspInit 1 */
  }
  else if (uartHandle->Instance == USART2)
  {
    /* USER CODE BEGIN USART2_MspInit 0 */

    /* USER CODE END USART2_MspInit 0 */
    /* USART2 clock enable */
    __HAL_RCC_USART2_CLK_ENABLE();

    __HAL_RCC_GPIOA_CLK_ENABLE();
    /**USART2 GPIO Configuration
    PA2     ------> USART2_TX
    PA15     ------> USART2_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_2 | GPIO_PIN_15;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF1_USART2;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

    /* USART2 DMA Init */
    /* USART2_TX Init */
    hdma_usart2_tx.Instance = DMA1_Channel4;
    hdma_usart2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
    hdma_usart2_tx.Init.PeriphInc = DMA_PINC_DISABLE;
    hdma_usart2_tx.Init.MemInc = DMA_MINC_ENABLE;
    hdma_usart2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
    hdma_usart2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
    hdma_usart2_tx.Init.Mode = DMA_NORMAL;
    hdma_usart2_tx.Init.Priority = DMA_PRIORITY_MEDIUM;
    if (HAL_DMA_Init(&hdma_usart2_tx) != HAL_OK)
    {
      Error_Handler();
    }

    __HAL_LINKDMA(uartHandle, hdmatx, hdma_usart2_tx);

    /* USART2 interrupt Init */
    HAL_NVIC_SetPriority(USART2_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USART2_IRQn);
    /* USER CODE BEGIN USART2_MspInit 1 */

    /* USER CODE END USART2_MspInit 1 */
  }
}

void HAL_UART_MspDeInit(UART_HandleTypeDef *uartHandle)
{

  if (uartHandle->Instance == USART1)
  {
    /* USER CODE BEGIN USART1_MspDeInit 0 */

    /* USER CODE END USART1_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_USART1_CLK_DISABLE();

    /**USART1 GPIO Configuration
    PA9     ------> USART1_TX
    PA10     ------> USART1_RX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9 | GPIO_PIN_10);

    /* USART1 DMA DeInit */
    HAL_DMA_DeInit(uartHandle->hdmatx);

    /* USART1 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USART1_IRQn);
    /* USER CODE BEGIN USART1_MspDeInit 1 */

    /* USER CODE END USART1_MspDeInit 1 */
  }
  else if (uartHandle->Instance == USART2)
  {
    /* USER CODE BEGIN USART2_MspDeInit 0 */

    /* USER CODE END USART2_MspDeInit 0 */
    /* Peripheral clock disable */
    __HAL_RCC_USART2_CLK_DISABLE();

    /**USART2 GPIO Configuration
    PA2     ------> USART2_TX
    PA15     ------> USART2_RX
    */
    HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2 | GPIO_PIN_15);

    /* USART2 DMA DeInit */
    HAL_DMA_DeInit(uartHandle->hdmatx);

    /* USART2 interrupt Deinit */
    HAL_NVIC_DisableIRQ(USART2_IRQn);
    /* USER CODE BEGIN USART2_MspDeInit 1 */
    /* USER CODE END USART2_MspDeInit 1 */
  }
}

/* USER CODE BEGIN 1 */

void Usart_SendString_integer2(uint8_t *str, uint32_t integer1, uint32_t integer2)
{
  uint8_t uart_str_ptr[100];
  sprintf(uart_str_ptr, "{%s:%d,%d\n}", str, integer1, integer2); // 兼容纸飞机串口助手显示曲线
  HAL_UART_Transmit_DMA(&huart1, uart_str_ptr, strlen(uart_str_ptr));
  HAL_UART_Transmit_DMA(&huart2, uart_str_ptr, strlen(uart_str_ptr));
}
void Usart_SendString_integer(uint8_t *str, uint32_t integer,uint32_t factor)
{

  uint8_t uart_str_ptr[100];
  uint32_t integer1,integer2;
  integer1 = integer/factor;
  integer2 = integer%factor;
  if(integer2 < factor/10 && integer2 > 0)
    sprintf(uart_str_ptr, "{%s:%d.0%d\n}", str, integer1, integer2);
  else
    sprintf(uart_str_ptr, "{%s:%d.%d\n}", str, integer1, integer2);// 兼容纸飞机串口助手显示曲线

  HAL_UART_Transmit_DMA(&huart1, uart_str_ptr, strlen(uart_str_ptr));
  HAL_UART_Transmit_DMA(&huart2, uart_str_ptr, strlen(uart_str_ptr));
}
void Usart_SendString(uint8_t *str)
{
  HAL_UART_Transmit_DMA(&huart1, str, sizeof(str) - 1);
  HAL_UART_Transmit_DMA(&huart2, str, sizeof(str) - 1);
}

void Uart_RecIT_Start(void)
{
  HAL_UART_Receive_IT(&huart1, rx_data1, 1);
  HAL_UART_Receive_IT(&huart2, rx_data2, 1);
}

uint8_t UartCheckAdd8(uint8_t *data_, uint8_t length)
{
  uint8_t add8 = 0;
  for (uint8_t i = 0; i < length; i++)
  {
    add8 += data_[i];
  }
  if (data_[length] == add8)
    return 1;
  else
    return 0;
}

void Uart_Send_Pack(uint8_t *data_, uint8_t len)
{
  uint8_t sum = len;
  uint8_t i = 0;

  Usart_Send_Buffer[0] = Master_Header2;
  Usart_Send_Buffer[1] = Master_Header1;
  Usart_Send_Buffer[2] = len;

  for (i = 0; i < len; i++)
  {
    Usart_Send_Buffer[i + 3] = *(data_ + i);
    sum += *(data_ + i);
  }

  Usart_Send_Buffer[i + 3] = sum;
  HAL_UART_Transmit_DMA(&huart1, Usart_Send_Buffer, i + 4);
  HAL_UART_Transmit_DMA(&huart2, Usart_Send_Buffer, i + 4);
}

void UR_Data_ParseBuffer(unsigned char *data_, unsigned char len)
{
  uint32_t Pressure = 0,Temperature = 0;
  controlinfo_S *rec = (controlinfo_S *)data_;
  UartRecData.DevAddr = rec->DevAddr;
  UartRecData.order = rec->order;
  memset(UartRecData.data, 0, 50);
  UsartContinuousSendFlag = UartRecData.order;
  switch (UartRecData.order)
  {
    if (SYS_DEVADDR == UartRecData.DevAddr)
    {
    case ORDER_GET_DEV_INF_hex:
      UartRecData.data[0] = SensorInfo.Pressure.val >> 24;
      UartRecData.data[1] = SensorInfo.Pressure.val >> 16;
      UartRecData.data[2] = SensorInfo.Pressure.val >> 8;
      UartRecData.data[3] = SensorInfo.Pressure.val;
	  UartRecData.data[4] = SensorInfo.Pressure.adc >> 8;
      UartRecData.data[5] = SensorInfo.Pressure.adc;
      UartRecData.data[6] = SensorInfo.Temperature.val >> 8;
      UartRecData.data[7] = SensorInfo.Temperature.val;
	  UartRecData.data[8] = SensorInfo.Temperature.adc >> 8;
      UartRecData.data[9] = SensorInfo.Temperature.adc;
      Uart_Send_Pack((uint8_t *)&UartRecData, len + 9);
      break;

    case ORDER_GET_DEV_INF_ascii: //
      Usart_SendString_integer2("PreTemp", SensorInfo.Pressure.val, SensorInfo.Temperature.val);
      break;

    case ORDER_GET_DEV_P_ascii:
      Pressure =  SensorInfo.Pressure.val - SensorInfo.Pressure.offset * SensorInfo.Pressure.factor;
      Usart_SendString_integer("Pre",Pressure,SensorInfo.Pressure.factor);
      break;

    case ORDER_GET_DEV_T_ascii:
      Temperature =  SensorInfo.Temperature.val - SensorInfo.Temperature.offset * SensorInfo.Temperature.factor;
      Usart_SendString_integer("Temp",SensorInfo.Temperature.val - SensorInfo.Temperature.offset,SensorInfo.Temperature.factor);
      break;

    case ORDER_GET_DEV_ADC:
      UartRecData.data[0] = SensorInfo.Pressure.adc >> 8;
      UartRecData.data[1] = SensorInfo.Pressure.adc;
      UartRecData.data[2] = SensorInfo.Temperature.adc >> 8;
      UartRecData.data[3] = SensorInfo.Temperature.adc;
      Uart_Send_Pack((uint8_t *)&UartRecData, len + 3);
      break;

    case ORDER_SET_DEV_ADDR:
      SYS_DEVADDR = rec->data[0];
      UartRecData.data[0] = SYS_DEVADDR;
      Uart_Send_Pack((uint8_t *)&UartRecData, len);
      break;
    }
    if (SYS_BROADCASTADDR == UartRecData.DevAddr)
    {
    case ORDER_GET_DEV_ADDR:
      UartRecData.data[0] = SYS_DEVADDR;
      Uart_Send_Pack((uint8_t *)&UartRecData, len);
      break;
    }
  }
}

/*************************************************
function name: void Uart_Unpack(unsigned char temp)
note:
0xA55A + length(1byte) + DevAddr(1byte) + cmd(1byte) + data(1byte~50byte) + crc(1byte)
length = DevAddr + cmd + data
*************************************************/
void Uart_Unpack(unsigned char urbuf)
{
#define rxbuffer_length 50
  static unsigned char RxBuffer[rxbuffer_length];
  static unsigned char last_ur_buf;
  static unsigned char RX_Count = 0;
  if (urbuf == Master_Header2 && last_ur_buf == Master_Header1)
  {
    RX_Count = 1;
    RxBuffer[0] = last_ur_buf;
  }
  last_ur_buf = urbuf;
  if (RX_Count > 0)
  {
    RxBuffer[RX_Count] = urbuf;
    if (RX_Count == 2) // length
    {
      if (RxBuffer[2] > rxbuffer_length)
      {
        RX_Count = 0;
        memset(RxBuffer, 0, rxbuffer_length);
        return;
      }
    }
    if (RX_Count >= RxBuffer[2] + 4)
    {
      RX_Count = 0;
      if (UartCheckAdd8((unsigned char *)RxBuffer + 2, RxBuffer[2] + 1) == 0)
      {
        memset(RxBuffer, 0, rxbuffer_length);
        return;
      }
      UR_Data_ParseBuffer((unsigned char *)RxBuffer + 3, RxBuffer[2]);
      memset(RxBuffer, 0, rxbuffer_length);
      return;
    }
    RX_Count++;
  }
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  if (huart->Instance == USART1)
  {
    /* add unpack code */
    Uart_Unpack(rx_data1[0]);
  }
  if (huart->Instance == USART2)
  {
    /* add unpack code */
    Uart_Unpack(rx_data2[0]);
  }
  Uart_RecIT_Start();
}
/* USER CODE END 1 */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
